<?php
class news extends module
{

//отключение общего кеширования если в запросе есть rs;1
function get_hash_code()
	{
	if($this->version==1 || $this->q_param['rss']!=0)return 0;
    $all_params=$this->block_id.$this->lang_id;
    foreach($this->view_param as $k=>$vp)
       	$all_params.=$k.$vp;
    if(is_array($this->q_param))
        foreach($this->q_param as $k=>$vp)
   	    	$all_params.=$k.$vp;
	return md5($all_params.$_GET["print"].$_POST["print"]);
    }
	
function get_site_host() {
	return "http://".$_SERVER['HTTP_HOST'];
}
function get_rss_title() {
	return $this->view_param['rss_title'];
}
function get_rss_description() {
	return $this->view_param['rss_description'];
}
//инициализация RSS; запускаем сборку, либо берем данные из кеша
function init_rss() {
	global $common_data_server,$encoding;
	$this->q_param['rss']="0";
	$cache_name=$this->get_hash_code();

	$filemtime=@filemtime($common_data_server."block_cache/block".$this->block_id."/".$cache_name.".html");
    if(!$filemtime || time()-$filemtime>$this->cache_time || $cache_name=="0")
    	{
        $this->body=$this->make_rss();
        if($this->cache_time!=0 && $cache_name!="0")
        	{
	        $this->make_cache($cache_name.".html");
            }
        }
    else 
    	{
        $this->get_cache($cache_name.".html");
        }

    header("Content-Type: application/xml; charset=".(($encoding != 'UTF8')?"windows-1251":"utf-8"));
	echo $this->body;
	exit;
}

function date_RFC822($val=0) {
	if ($val==0)
		return date('D, d M Y G:i:s O');
	else
		return date('D, d M Y G:i:s O',$val);
}
//сборка RSS
function make_rss() {
	$tmpl_file="rss.vtmpl";
	if (!$this->check_template($tmpl_file)) $this->body=$this->error;
	else {
		$_SERVER['QUERY_STRING']=str_replace("rss".$this->tarea_id."=1","",$_SERVER['QUERY_STRING']);
		$host = $this->get_site_host();
		$this->set_template($tmpl_file);
		$this->template->setVar("xml_header",'<?xml version="1.0" encoding="windows-1251"?>');
		$this->template->setVar("rss_title",$this->get_rss_title());
		$this->template->setVar("rss_description",$this->get_rss_description());
		$this->template->setVar("rss_link",$host);
		$this->template->setVar("rss_date",$this->date_RFC822());
		$data = sql_select("SELECT NEWS.TITLE as title, NEWS.CONTENT_ID, ANNOUNCE as DESCRIPTION,NEWS_DATE from NEWS, CONTENT_MAP WHERE VERSION={$this->version} AND LANG_ID={$this->lang_id} AND NEWS.CONTENT_ID=CONTENT_MAP.CONTENT_ID AND INF_BLOCK_ID={$this->block_id} order by NEWS_DATE desc");
		foreach ($data as $k=>$v) {
			$path_and_area = $this->make_path($v['CONTENT_ID'],$this->block_id);
			$data[$k]['guid']=$host.$_SERVER['PHP_SELF']."/{$path_and_area["path"]}?".make_query_string(array("id{$path_and_area["area"]}"=>$v["CONTENT_ID"]));
			$data[$k]['link']=$data[$k]['guid'];
			if(preg_match("/^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$v['NEWS_DATE'],$matches)) {
				$data[$k]['date']=$this->date_RFC822(mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]));
			}
		}
		$this->template->setLoop("rss_data",$data);
		
		return $this->template->grab();
	}
}
// content_init
function content_init()
{
    //вызов метода, выдающего RSS
	if($this->q_param["rss"]=="1") {
    	$this->init_rss();
    }
	
	global $common_data_server;
	$this->template_path="{$common_data_server}module_templates/news/{$this->view_param["template"]}/";

	// Задаем правильный порядок сортировки
	if($this->view_param["sort"]=="desc")
    {
		$this->sort="DESC";
	}
	// Подготавливаем правильный оффсет для лимита
	if(!is_numeric($this->q_param["from"]) || intval($this->q_param["from"])<=0)
    {
		$this->from=0;
	}
    else
    {
		$this->from=intval($this->q_param["from"])-1;
	}

	$this->from*=$this->view_param["item_number"];
	// Проверяем наличие шаблонов, объявляем основной шаблон и запускаем обработчика
	if($this->view_param["view_mode"]=="list" && !is_numeric($this->q_param["id"]))
    {
		if(!$this->check_template("pager.vtmpl") || !$this->set_template("list.vtmpl"))
        {
			$this->body=$this->error;
		}
        else
        {
			$this->body=$this->news_list();
		}
	}
    elseif($this->view_param["view_mode"]=="archive" && !is_numeric($this->q_param["id"]))
    {
		if(!$this->check_template("pager.vtmpl") || !$this->check_template("archive.vtmpl") || !$this->set_template("list.vtmpl"))
        {
			$this->body=$this->error;
		}
        else
        {
			$this->body=$this->news_archive();
		}
	}
    else
    {
		if(!$this->set_template("item.vtmpl"))
        {
			$this->body=$this->error;
		}
        else
        {
			$this->body=$this->news_item();
		}
	}
}
function make_rss_vars(&$template) {
        $rss_link = $this->get_site_host().$_SERVER['PHP_SELF']."?rss{$this->tarea_id}=1";
        $template->setVar('RSS_LINK', $rss_link);
        $this->link='<link href="'.$rss_link.'" rel="alternate" type="application/rss+xml" title="'.$this->view_param['rss_title'].'" />';
}
// news_list
function news_list()
{
	if( intval($this->view_param["show_rss"]) != 0) {
		$this->make_rss_vars($this->template);
	    }    

    $list=sql_select($this->make_sql("list"));
	foreach($list as $k=>$item)
    {
		$list[$k]=$this->make_item($list[$k],1);
	}
	$this->template->setLoop("list",$list);

	if($this->view_param["is_lister"])
    {
		$counter=sql_select($this->make_sql("list_counter"));
		$this->make_pager($counter[0]["COUNTER"]);
	}
	$path_and_area=$this->make_path();
	$this->template->setVar("arch_link",$path_and_area["path"]);
	$this->title=$list[0]["TITLE"];
	return $this->template->grab();
}
// news_archive
function news_archive()
{
	if( intval($this->view_param["show_rss"]) != 0) {
		$this->make_rss_vars($this->template);
	    }    
	// Формируем правильные даты начала и окончания
	preg_match("/^(\d\d)\.(\d\d)\.(\d\d\d\d)$/",$this->q_param["afrom"],$d);
	if(is_numeric($d[1]))
    {
		$this->afrom=$d[3].$d[2].$d[1]."000000";
	}
    else
    {
		$this->afrom=date("Ymd",mktime(0,0,0,(date("m")-1),date("d"),date("Y")))."000000";
		$this->q_param["afrom"]=date("d.m.Y",mktime(0,0,0,(date("m")-1),date("d"),date("Y")));
	}
	
	preg_match("/^(\d\d)\.(\d\d)\.(\d\d\d\d)$/",$this->q_param["ato"],$d);
	if(is_numeric($d[1])){
		$this->ato=$d[3].$d[2].$d[1]."250000";
	}
    else
    {
		$this->ato=date("Ymd",mktime(0,0,0,(date("m")),date("d"),date("Y")))."250000";
		$this->q_param["ato"]=date("d.m.Y",mktime(0,0,0,(date("m")),date("d"),date("Y")));
	}

	// Собираем шапочку
	$archive_tmpl=new vlibTemplate();
	$archive_tmpl->newTemplate($this->template_path."archive.vtmpl");
	$archive_tmpl->setVar("afrom",$this->q_param["afrom"]);
	$archive_tmpl->setVar("ato",$this->q_param["ato"]);
	$archive_tmpl->setVar("tarea_id",$this->tarea_id);
	$archive=$archive_tmpl->grab();
	$this->template->setVar("archive",$archive);

	// Собираем список
	$list=sql_select($this->make_sql("archive"));
	foreach($list as $k=>$item){
		$list[$k]=$this->make_item($list[$k],1);
	}
	$this->template->setLoop("list",$list);

	if($this->view_param["is_lister"]){
		$counter=sql_select($this->make_sql("archive_counter"));
		$this->make_pager($counter[0]["COUNTER"]);
	}

	$this->title=$list[0]["TITLE"];
	return $this->template->grab();
}
// news_item
function news_item(){
	if( intval($this->view_param["show_rss"]) != 0) {
		$this->make_rss_vars($this->template);
	    }    
	$item=sql_select("SELECT NEWS.* FROM NEWS, CONTENT_MAP WHERE NEWS.CONTENT_ID={$this->q_param["id"]} AND VERSION={$this->version} AND LANG_ID={$this->lang_id} AND NEWS.CONTENT_ID=CONTENT_MAP.CONTENT_ID AND INF_BLOCK_ID={$this->block_id}");
	
	if(count($item) != 0)
	{
    	$this->template->hash2vlib($this->make_item($item[0]));
    	$this->title=$item[0]["TITLE"];
    
    	$path_and_area=$this->make_path();
    
    	if($this->is_print==1){
    		$this->template->setVar("is_print",1);
    	}
	}
	else 
	{
	   $this->template->setVar("ERROR", 'ERR_NOT_FOUND');
	}
	
	return $this->template->grab();
}
// set_template
function set_template($tmpl){
	if(!$this->check_template($tmpl)){
		return 0;
	}else{
		$this->template=new vlibTemplate();
		$this->template->newTemplate($this->template_name);
		$this->template->setVar("tarea_id",$this->tarea_id);
	}
	return 1;
}
// check_template
function check_template($tmpl){
	$full_name=$this->template_path.$tmpl;
	if(!file_exists($full_name)){
		$this->error.="Шаблон '{$this->template_path}{$tmpl}' отсутствует<br>";
		return 0;
	}
	$this->template_name=$full_name;
	return 1;
}
// make_item
function make_item($item,$is_list=""){
	preg_match("/(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/",$item["NEWS_DATE"],$d);
	$item["NEWS_DATE"]=date($this->view_param["date_format"],mktime($d[4],$d[5],$d[6],$d[2],$d[3],$d[1]));

	if($is_list){
		$path_and_area=$this->make_path($item["CONTENT_ID"],$item["INF_BLOCK_ID"]);
		$item["URL"]="{$path_and_area["path"]}?".make_query_string(array("id{$path_and_area["area"]}"=>$item["CONTENT_ID"]));
	}

	$item["BACK_URL"]="index.php?".make_query_string(array(
		"id{$this->tarea_id}"=>"",
		"afrom{$this->tarea_id}"=>$this->q_param["afrom"],
		"ato{$this->tarea_id}"=>$this->q_param["ato"],
		"from{$this->tarea_id}"=>$this->q_param["from"],
	));
	return $item;
}
// make_path
// Если не $CONTENT_ID, то функция пытаетcя собрать путь к архиву новостей
// В противном случае собирается путь к новостям в главной области главного блока указанной новости
// $MAIN_BLOCK_ID - идентификатор главного блока для новости с указанным $CONTENT_ID
// возвращает array("path"=>$redir_path,"area"=>$redir_tarea_id), то есть путь и идентификатор области
function make_path($CONTENT_ID="",$MAIN_BLOCK_ID=""){
	static $paths; // Кэш путей для оптимизации работы модуля
	if(!$MAIN_BLOCK_ID || !$paths[$MAIN_BLOCK_ID]){
		$param_value=sql_select("
			SELECT
				PV.PARAM_VALUE_ID,MP.MODULE_PARAM_ID
			FROM
				MODULE_PARAM MP,
				PRG_MODULE PM,
				PARAM_VALUE PV
			WHERE
				MP.SYSTEM_NAME='view_mode' AND
				PV.VALUE=".( $CONTENT_ID ? "'list'" : "'archive'" )." AND
				PV.MODULE_PARAM_ID=MP.MODULE_PARAM_ID AND
				MP.PRG_MODULE_ID=PM.PRG_MODULE_ID AND
				PM.CLASS_NAME = 'news'
			");
		if(is_numeric($param_value[0]["MODULE_PARAM_ID"])){
			$page_id = sql_select("
				SELECT
					PA.PAGE_ID as PAGE_ID,
					PA.TEMPLATE_AREA_ID as TAREA_ID
				FROM
					PAGE_AREA PA,
					PAGE P,
					TEMPLATE_AREA TA,
					PAGE_AREA_PARAM PAP
				WHERE
					PA.INF_BLOCK_ID=".( $CONTENT_ID ? $MAIN_BLOCK_ID : $this->block_id )." and
					P.SITE_ID = {$this -> site_id} and
					P.VERSION = {$this -> version} and
					P.LANG_ID = {$this -> lang_id} and
					P.PAGE_ID = PA.PAGE_ID and
					P.VERSION = PA.VERSION and
					PA.TEMPLATE_AREA_ID = TA.TEMPLATE_AREA_ID and
					TA.IS_MAIN=1 AND
					PAP.PAGE_ID=PA.PAGE_ID AND
					PAP.VERSION=PA.VERSION AND
					PAP.TEMPLATE_AREA_ID=PA.TEMPLATE_AREA_ID AND
					PAP.MODULE_PARAM_ID={$param_value[0]["MODULE_PARAM_ID"]} AND
					PAP.VALUE={$param_value[0]["PARAM_VALUE_ID"]}
				");
		}
		if($page_id[0]['PAGE_ID']!="" && ($page_id[0]['PAGE_ID']!=$this->page_id || $page_id[0]['TAREA_ID']!=$this->tarea_id)){
			$redir_path=$this->go_to_page($page_id[0]['PAGE_ID']);
			$redir_tarea_id=$page_id[0]['TAREA_ID'];
		}else{
			if($CONTENT_ID)$redir_path="index.php";
		}
		if(!$redir_tarea_id){
			$redir_tarea_id=$this->tarea_id;
		}
		if($MAIN_BLOCK_ID){
			$paths[$MAIN_BLOCK_ID]["path"]=$redir_path;
			$paths[$MAIN_BLOCK_ID]["area"]=$redir_tarea_id;
		}
	}else{
		$redir_path=$paths[$MAIN_BLOCK_ID]["path"];
		$redir_tarea_id=$paths[$MAIN_BLOCK_ID]["area"];
	}
	return array("path"=>$redir_path,"area"=>$redir_tarea_id);
}
// make_pager
function make_pager($counter){
	if($counter>$this->view_param["item_number"]){
		$this->template->setVar("pager",page_navigation($this->view_param["item_number"], $counter, "from".$this->tarea_id, $this->template_path."pager.vtmpl"));
	}
}
// Формируем sql для случаев списка новостей, архива новостей и общего количества новостей для этих случаев
function make_sql($mode){
	$template="SELECT <fields> FROM CONTENT_MAP, NEWS
			, CONTENT_MAP CM2, INF_BLOCK, PRG_MODULE
		WHERE CONTENT_MAP.INF_BLOCK_ID={$this->block_id}
			AND NEWS.CONTENT_ID=CONTENT_MAP.CONTENT_ID
			AND NEWS.VERSION={$this->version}
			AND NEWS.LANG_ID={$this->lang_id}

			AND CM2.CONTENT_ID=NEWS.CONTENT_ID
			AND CM2.IS_MAIN=1
			AND CM2.INF_BLOCK_ID=INF_BLOCK.INF_BLOCK_ID
			AND INF_BLOCK.PRG_MODULE_ID=PRG_MODULE.PRG_MODULE_ID
			AND PRG_MODULE.CLASS_NAME='news'
			<where>
		<order>
		<limit>";
	$pattern=array("/<fields>/","/<where>/","/<order>/","/<limit>/");
	if($mode=="list"){
		$replace=array("NEWS.*,INF_BLOCK.INF_BLOCK_ID","","ORDER BY NEWS.NEWS_DATE {$this->sort}","LIMIT {$this->from},{$this->view_param["item_number"]}");
	}elseif($mode=="list_counter"){
		$replace=array("COUNT(*) AS COUNTER","","","");
	}elseif($mode=="archive"){
		$replace=array("NEWS.*,INF_BLOCK.INF_BLOCK_ID","AND NEWS.NEWS_DATE>='{$this->afrom}' AND NEWS.NEWS_DATE<={$this->ato}","ORDER BY NEWS.NEWS_DATE {$this->sort}","LIMIT {$this->from},{$this->view_param["item_number"]}");
	}elseif($mode=="archive_counter"){
		$replace=array("COUNT(*) AS COUNTER","AND NEWS.NEWS_DATE>='{$this->afrom}' AND NEWS.NEWS_DATE<={$this->ato}","","");
	}
	$sql=preg_replace($pattern,$replace,$template);
	return $sql;
}

}
?>